package de.hub.sar.itsec.sslfetcher;

import java.util.List;
import de.hub.sar.itsec.sslfetcher.fetcher.FetchFailsException;
import de.hub.sar.itsec.sslfetcher.fetcher.IFetcher;
import de.hub.sar.itsec.sslfetcher.hosts.Host;
import de.hub.sar.itsec.sslfetcher.log.Logger;
import de.hub.sar.itsec.sslfetcher.saver.ISaver;
import de.hub.sar.itsec.sslfetcher.utils.Converter;

public class LoadRunner implements Runnable {
	private ISaver saver;
	private IFetcher fetcher;
	private final Host host;
	private final ILoadListener listener;
	
	public LoadRunner(final Host host, ILoadListener listener) {
		this.host = host;
		this.listener = listener;
	}

	void setSaver(ISaver saver) {
		this.saver = saver;
	}

	void setFetcher(IFetcher fetcher) {
		this.fetcher = fetcher;
	}

	@Override
	public void run() {
		List<byte[]> certs;
		
		try {
			certs = fetcher.getCerts(host.getHost(), host.getDomain(), host.getPort());
		} catch (FetchFailsException e) {
			Logger.getInstance().error("FAILED: " + host.getHost() + " - " + host.getDomain());
			this.listener.onFailed(this.host);
			return;
		}
		
		int i = 0;
		for (byte[] cert : certs) {
			saver.save(Converter.hostToFolderName(host.getDomain()) + "-" + i++, cert);
			Logger.getInstance().info("DONE: " + host.getHost() + " - " + host.getDomain());
		}
		
		this.listener.onDone(this.host);
	}

}
